package com.xx.sign.interceptor;

import com.google.common.collect.Maps;
import com.xx.sign.util.SignToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author fanjj
 * @date 2017/10/26
 */
public class SignCheckInterceptor extends HandlerInterceptorAdapter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        PrintWriter printWriter = null;
        try {
            Map<String, String> map = Maps.newHashMap();
            map.put(SignToken.TIME_STAMP, request.getParameter(SignToken.TIME_STAMP));
            map.put(SignToken.SECURITY_VERSION_STRING, request.getParameter(SignToken.SECURITY_VERSION_STRING));
            map.put(SignToken.APP_KEY, request.getParameter(SignToken.APP_KEY));
            map.put("parameter", request.getParameter("parameter"));
            String appSecret = "111";
            SignToken.validate(map, appSecret, request.getParameter(SignToken.SIGN));
            return super.preHandle(request, response, o);
        } catch (Exception e) {
            logger.error("SignCheckInterceptor preHandle ERROR: {}", e.getMessage(), e);
            response.setCharacterEncoding("utf-8");
            printWriter = response.getWriter();
            printWriter.write("安全协议校验失败:" + e.getMessage());
            return false;
        } finally {
            if (printWriter != null)
                printWriter.close();
        }
    }
}
